package com.mooltik;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import com.mooltik.content.Notes;

public class EditorActivity extends Activity implements View.OnClickListener {
    private EditText editText;
    private GestureDetector detector;
    private Intent intent;

    //swipe gesture constants
    private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.editor);

        intent = getIntent();

        setupEditText();

        setupGesture();

    }


    private void setupGesture() {
        detector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {

            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

                if (Math.abs(e1.getY() - e2.getY()) < SWIPE_MAX_OFF_PATH && e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    saveAndExit();
                    return true;
                } else if (Math.abs(e1.getX() - e2.getX()) < SWIPE_MAX_OFF_PATH && e2.getY() - e1.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
                    hideSoftKeyboard();
                    return true;
                }

                return false;
            }

        });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        super.dispatchTouchEvent(event);

        if (detector.onTouchEvent(event))
            return true;
        else
            return false;
    }

    private void setupEditText() {

        editText = (EditText) findViewById(R.id.edit);

        String title = intent.getStringExtra(Notes.TITLE);
        String note = intent.getStringExtra(Notes.NOTE);
        editText.setText(title + "\n" + note);


        // move cursor and add newline if needed
        if (note.length() != 0) {
            String lastChar = note.substring(note.length() - 1);
            if (!lastChar.equals("\n")) {
                editText.append("\n");
            }
        }
        editText.setSelection(editText.length());

        // format text
        Spannable str = editText.getText();
        str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, title.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        str.setSpan(new ForegroundColorSpan(Color.rgb(14, 104, 220)), 0, title.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        str.setSpan(new StyleSpan(android.graphics.Typeface.NORMAL), title.length(), str.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        str.setSpan(new AbsoluteSizeSpan(18), 0, title.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        //str.setSpan(new UnderlineSpan(), 0, title.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);


//        showSoftKeyboard();
    }

    private void showSoftKeyboard() {
        InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        mgr.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
    }

    private void hideSoftKeyboard() {
        InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        mgr.hideSoftInputFromWindow(editText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }


    public void onClick(View view) {
        if (view.getId() == R.id.saveButton) {
            saveAndExit();
        } else if (view.getId() == R.id.cancelButton) {
            setResult(RESULT_CANCELED, intent);
            finish();
        }
    }

    private void saveAndExit() {
        String str = editText.getText().toString();

        String title = null;
        String text = null;

        if (str.length() > 0) {
            int returnPos = str.indexOf("\n");
            if (returnPos != -1) {
                title = str.substring(0, returnPos);
                text = str.substring(returnPos + 1, str.length());
            } else {
                title = str;
            }
        }

        intent.putExtra(Notes.TITLE, title);
        intent.putExtra(Notes.NOTE, text);
        setResult(RESULT_OK, intent);

        // hide keyboard to escape display blinking at main activity
        hideSoftKeyboard();

        finish();
    }
}
